//
//  CrackData.m
//  ofoCrack
//
//  Created by admin on 17/2/22.
//  Copyright © 2017年 Wheng. All rights reserved.
//

#import "CrackData.h"

static CrackData *crackData = nil;

@implementation CrackData

+ (CrackData *)singleton {
    @synchronized (self) {
        if (crackData == nil) {
            crackData = [[self alloc]init];
            
            [crackData createContext];
        }
    }
    return crackData;
}

- (NSString *)selectBicycleDataWithNumber:(NSString *)number {
    NSFetchRequest *request = [[NSFetchRequest alloc]init];
    
    request.entity = [NSEntityDescription entityForName:@"Bicycle" inManagedObjectContext:self.context];
    request.predicate = [NSPredicate predicateWithFormat:@"number like %@",number];
    
    NSArray *temp = [self.context executeFetchRequest:request error:nil];
    
    BicycleModel *model = [temp lastObject];
    
    return model.password;
}

- (void)addBicycleData:(BicycleModel *)model {
    NSManagedObject *bicycle = [NSEntityDescription insertNewObjectForEntityForName:@"Bicycle" inManagedObjectContext:self.context];
    [bicycle setValue:model.number forKey:@"number"];
    [bicycle setValue:model.password forKey:@"password"];
    NSError *error = nil;
    BOOL success = [self.context save:&error];
    if (!success) {
        [NSException raise:@"Get Error" format:@"%@",[error localizedDescription]];
    }
}

- (void)createContext {
    NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
    NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
    
    NSString *docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    NSURL *url = [NSURL fileURLWithPath:[docs stringByAppendingPathComponent:@"bicycle.data"]];
    
    NSError *error = nil;
    
    NSPersistentStore *store = [psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error];
    
    if (store == nil) {
        [NSException raise:@"Add Error" format:@"%@",[error localizedDescription]];
    }
    
    self.context = [[NSManagedObjectContext alloc]initWithConcurrencyType:(NSPrivateQueueConcurrencyType)];
    self.context.persistentStoreCoordinator = psc;
}

@end
